import request from 'supertest';
import userCenterService from './src/index';
import { database } from './src/config/database';
import { UserDAO } from './src/dao/UserDAO';
import { SystemDAO } from './src/dao/SystemDAO';
import bcryptjs from 'bcryptjs';
import { Types } from 'mongoose';
import User from './src/models/user';
import System, { SystemStatus } from './src/models/system';
import Session from './src/models/session';

async function debugAdminLogin() {
  try {
    await database.connect();
    await userCenterService.init();
    const app = userCenterService.getApp().callback();

    const userDAO = new UserDAO();
    const systemDAO = new SystemDAO();

    // 清理测试数据
    await User.deleteMany({});
    await System.deleteMany({});
    await Session.deleteMany({});

    // 创建测试系统
    const testSystem = await systemDAO.create({
      systemName: '测试系统',
      systemCode: 'test-system',
      systemType: 'web',
      version: '1.0.0',
      description: '用于测试的系统',
      allowedOrigins: ['http://localhost:3000'],
      status: SystemStatus.ACTIVE,
      createdBy: new Types.ObjectId()
    });

    // 创建超级管理员用户
    const superAdminPassword = await bcryptjs.hash('superadmin123', 10);
    const superAdminUser = await userDAO.create({
      username: 'superadmin',
      email: 'superadmin@example.com',
      password: superAdminPassword,
      realName: '超级管理员',
      phone: '13900139000',
      status: 'active',
      adminLevel: 'super',
      isSuperAdmin: true
    });

    console.log('Created superadmin user:', {
      username: superAdminUser.username,
      adminLevel: superAdminUser.adminLevel,
      isSuperAdmin: superAdminUser.isSuperAdmin,
      status: superAdminUser.status
    });

    // 测试管理员登录
    const response = await request(app)
      .post('/api/auth/admin/login')
      .send({
        username: 'superadmin',
        password: 'superadmin123',
        systemCode: 'test-system'
      });

    console.log('Response status:', response.status);
    console.log('Response body:', JSON.stringify(response.body, null, 2));

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await database.disconnect();
  }
}

debugAdminLogin();
